//
// Created by shanshi on 30/6/2025.
//

#ifndef THREAD_CACHE_H
#define THREAD_CACHE_H
#include <iostream>
#include <array>
#include "common.h"
namespace memory_pool {
    class thread_cache {
    public:
        static thread_cache* get_instance() {
            // 懒汉式
            static thread_local thread_cache instance;
            return &instance;
        }
        void* allocate(size_t size);
        void deallocate(void* ptr, size_t size);
    private:
        thread_cache() {
            // 初始化自由链表
            free_list.fill(nullptr);
            free_list_sizes.fill(0);
        };
        // 从central cache中获取内存
        void* fetch_from_central_cache(size_t index);
        // 归还内存给central cache
        void return_to_central_cache(void* start, size_t size);
        // 计算需要批量申请的内存块
        size_t compute_num_to_fetch(size_t index);
        // 是否需要归还内存给central cache
        bool should_tune(size_t index);
    private:
        std::array<void*, FREE_LIST_SIZE> free_list;
        std::array<size_t, FREE_LIST_SIZE> free_list_sizes;
    };
}


#endif //THREAD_CACHE_H
